package Com.Hupochuan.Uil.Util;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DoTool {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private DoResponse doResponse;
	
	/*
	 * 构造方法 设置 request
	 */
	public DoTool(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
		this.doResponse = new DoResponse(response);
	}
	
	/*
	 * 获得即将响应的内容
	 */
	public String getContent(){
		return this.doResponse.getContent();
	}
	
	/*
	 * HTML转码
	 */
	public String htmlEncode(String html){
		
		//去除文本中的Tab
		html = html.replaceAll("\t", "");
		
		//去除文本中的换行
		html = html.replaceAll("\r\n", "");
		
		return html;
	}
	
	/*
	 * Do转发页面
	 */
	public void doForward(String url){
		try {
			this.request.getRequestDispatcher(url).forward(this.request,this.doResponse);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 转发页面
	 */
	public void forward(String url){
		try {
			this.request.getRequestDispatcher(url).forward(this.request,this.response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 包含页面
	 */
	public void include(String url){
		try {
			this.request.getRequestDispatcher(url).include(this.request,this.response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 重定向
	 */
	public void redirect(String url){
		try {
			this.response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 发送错误
	 */
	public void sendError(int no){
		try {
			this.response.sendError(no);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 获得IP
	 */
	public String getIp(){
		return request.getRemoteAddr();
	}
	
	/*
	 * 获得参数
	 */
	public String getPara(String name){
		String value = "";
		
		//获得参数
		String para = request.getParameter(name);
		
		//如果参数不是空
		if(para != null){
			value = para;
		}
		return value;
	}
	
	/*
	 * 获得地址栏中文参数
	 */
	public String getUrlChinesePara(String name){
		String value = this.getPara(name);
		try {
			value = new String(value.getBytes("iso8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/*
	 * 获得long参数
	 */
	public long getLongPara(String name){
		long value = 0;
		
		//获得参数
		String para = this.getPara(name);
		
		//尝试转换为数字类型
		try{
			value = Long.parseLong(para);
		}
		catch(NumberFormatException e){}
		return value;
	}
	
	/*
	 * 获得boolean参数
	 */
	public boolean getBooleanPara(String name){
		//获得参数
		String para = this.getPara(name);
		
		//转换为布尔类型 并返回
		return Boolean.parseBoolean(para);
	}
	
	/*
	 * 获得float参数
	 */
	public float getFloatPara(String name){
		float value = 0;
		
		//获得参数
		String para = request.getParameter(name);
		
		//尝试转换为数字类型
		try{
			value = Float.parseFloat(para);
		}
		catch(NumberFormatException e){}
		return value;
	}
	
	/*
	 * 设置Attribute
	 */
	public void setAttr(String name,Object o){
		this.request.setAttribute(name, o);
	}
	
	/*
	 * 获得Attribute
	 */
	public Object getAttr(String name){
		return this.request.getAttribute(name);
	}
	
	/*
	 * 清除Attribute
	 */
	public void clearAttr(String name){
		this.request.removeAttribute(name);
	}
	
	/*
	 * 设置Session
	 */
	public void setSess(String name,Object o){
		this.request.getSession().setAttribute(name, o);
	}
	
	/*
	 * 获得Session
	 */
	public Object getSess(String name){
		return this.request.getSession().getAttribute(name);
	}
	
	/*
	 * 清除Session
	 */
	public void removeSess(String name){
		this.request.getSession().removeAttribute(name);
	}
	
	/*
	 * 发送给客户端一个图片
	 */
	public void sendImg(RenderedImage image){
		try {
		    ImageIO.write(image, "JPEG", this.response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
	
	/*
	 * 发送给客户端一段数据
	 */
	public void sendMsg(String msg){
		try {
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = this.response.getWriter();
			out.print(msg);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 发送给客户端一段hash数据
	 */
	public void sendMsg(Hashtable<String,String> msg){
		//返回缓冲器
		StringBuffer sendBuffer = new StringBuffer();
		try {
			sendBuffer.append("{");
	        for(String key: msg.keySet()){
	        	sendBuffer.append("\"");
	        	sendBuffer.append(key);
	        	sendBuffer.append("\"");
	        	sendBuffer.append(":");
	        	sendBuffer.append("\"");
				sendBuffer.append(URLEncoder.encode(msg.get(key),"utf-8"));
	        	sendBuffer.append("\"");
	        	sendBuffer.append(",");
	        }
	        int sendBufferLength = sendBuffer.length();
	        //长度大于0 那就去除最后一个","
	        if(sendBufferLength > 0){
	        	sendBuffer.delete(sendBufferLength - 1,sendBufferLength);
	        }
	        sendBuffer.append("}");
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        //String returnString = sendBuffer.toString();
        //returnString = returnString.substring(0, returnString.length()-1);
        
		//发送回客户端页面
		this.sendMsg(sendBuffer.toString());
	}

	/*
	 *获得根目录(绝对路径) 
	 */
	private String getRootPath(){
		return request.getSession().getServletContext().getRealPath("");
	}
	
	/*
	 * 保存Html文件
	 */
	public boolean saveHtml(String htmlPath,String content){
		String rootPath = this.getRootPath();
		try{
			//html文件
			File htmlFile = new File(rootPath + htmlPath);
			
			//html文件夹
			File htmlFolder = htmlFile.getParentFile();
			
			//如果html文件夹不存在 那就创建一个 
			if(!htmlFolder.exists()){ 
				htmlFolder.mkdirs(); 
			}
			
			//文件存在那就删除
			if(htmlFile.exists()){
				htmlFile.delete();
			}
			
			//创建文件
			htmlFile.createNewFile();
			
			//获得输出流
			FileOutputStream fos = new FileOutputStream(htmlFile);
			
			fos.write(content.getBytes("utf-8"));//写入文件内容  
			fos.flush();
			fos.close();
			return true;
		} catch (IOException e) {     
			return false;
		}
	}
	
	/*
	 * 移动文件
	 */
	public boolean removieTempImg(String tempImgName, String newPath){
		String rootPath = this.getRootPath();
		String tempImgPath = "/image/temp/"+ tempImgName;
		
		//临时文件
		File tempFile = new File(rootPath + tempImgPath);
		
		//如果临时文件存在
		if(tempFile.exists()){
			//新的文件
			File newFile = new File(rootPath + newPath);// + "." + this.getFileExtension(tempFile));
			
			//新的文件夹
			File newFolder = newFile.getParentFile();
			
			//如果新的文件夹不存在 那就创建一个 
			if(!newFolder.exists()){ 
				newFolder.mkdirs(); 
			}
			
			//如果新的文件存在 那就删除
			if(newFile.exists()){ 
				newFile.delete();
			}
			
			//移动临时文件
			tempFile.renameTo(newFile);
			return true;
		}
		else{
			return false;
		}
	}
	
	/*
	 * 删除文件
	 */
	public void deleteFile(String deletePath){
		String rootPath = this.getRootPath();
		
		//图片文件
		File deleteFile = new File(rootPath + deletePath);
		
		//如果要删除的文件存在
		if(deleteFile.exists()){ 
			deleteFile.delete();
		}
	}
	
	/*
	 * 获取文件扩展名
	 */
	public String getExtName(String fileName) {
		if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		} else {
			return "";
		}
	}
	
	private List<String> pathParaList;//获得路径参数列表
	
	/*
	 * 获得路径参数 初始化pathParaList
	 */
	public String getPathPara(int no){
		
		if(this.pathParaList == null){
			//创建List
			this.pathParaList = new Vector<String>();
			
			//获得请求路径
			String url = this.request.getRequestURI();
			//遍历"/"分隔开的每个参数
			for(String para : url.split("/")){
				
				//如果参数不为空
				if(!para.equals("")){
					
					//参数解码
					//para = URLDecoder.decode(para,"iso8859-1");
					//para = new String(para.getBytes("iso8859-1"),"utf-8");
					this.pathParaList.add(para);
				}
			}
		}
		
		//防止数组下标越界
		if(no >= this.pathParaList.size()){
			return "";
		}
		
		//防止空指针异常
		String para = this.pathParaList.get(no);
		if(para == null){
			return "";
		}
		else{
			return para;
		}
	}
	
	/*
	 * 获得路径参数 返回Long
	 */
	public long getLongPathPara(int no){
		long value = 0;
		
		//获得参数
		String para = this.getPathPara(no);
		
		//尝试转换为数字类型
		try{
			value = Long.parseLong(para);
		}
		catch(NumberFormatException e){}
		return value;
	}
	
	/*
	 * 查找路径参数
	 */
	public String findPathPara(String key){
		for(String pathPara : pathParaList){
			if(pathPara.startsWith(key)){
				return pathPara.replace(key,""); 
			}
		}
		return "";
	}
	
	/*
	 * 查找路径参数
	 */
	public String findUrlChinesePathPara(String key){
		String value = this.findPathPara(key);
		try {
			value =  URLDecoder.decode(value,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	/*
	 * 查找路径参数 返回Long
	 */
	public long findLongPathPara(String key){
		long value = 0;
		
		//获得参数
		String para = this.findPathPara(key);
		
		//尝试转换为数字类型
		try{
			value = Long.parseLong(para);
		}
		catch(NumberFormatException e){}
		return value;
	}

	/*
	 * 获得请求对象
	 */
	public HttpServletRequest getRequest() {
		return request;
	}

	/*
	 * 获得响应对象
	 */
	public HttpServletResponse getResponse() {
		return response;
	}
}
